import os
import json
from pathlib import Path
from typing import Optional, Dict, Any, Type, TypeVar, Generic, Union

from pydantic import BaseModel
from .models import AppConfig, MenuConfig, ToolbarConfig, DockWidgetConfig, ButtonConfig

T = TypeVar('T', bound=BaseModel)

class ConfigManager:
    """配置管理器，负责加载和保存配置"""
    
    def __init__(self, config_dir: str = "config"):
        self.config_dir = Path(config_dir)
        self.config_dir.mkdir(exist_ok=True)
        self.app_config: Optional[AppConfig] = None
        
    def load_config(self, model_cls: Type[T], name: str) -> T:
        """加载指定名称的配置"""
        config_path = self.config_dir / f"{name}.json"
        
        # 如果配置文件不存在，返回默认配置
        if not config_path.exists():
            return model_cls()
        
        try:
            with open(config_path, "r", encoding="utf-8") as f:
                data = json.load(f)
            return model_cls.model_validate(data)
        except Exception as e:
            print(f"加载配置文件 {name}.json 失败: {str(e)}")
            return model_cls()
    
    def save_config(self, config: BaseModel, name: str) -> bool:
        """保存配置到文件"""
        config_path = self.config_dir / f"{name}.json"
        
        try:
            # 确保目录存在
            config_path.parent.mkdir(parents=True, exist_ok=True)
            
            # 序列化配置并保存
            with open(config_path, "w", encoding="utf-8") as f:
                f.write(config.model_dump_json(indent=2))
            return True
        except Exception as e:
            print(f"保存配置文件 {name}.json 失败: {str(e)}")
            return False
    
    def load_app_config(self) -> AppConfig:
        """加载应用程序配置"""
        self.app_config = self.load_config(AppConfig, "app")
        return self.app_config
    
    def save_app_config(self) -> bool:
        """保存应用程序配置"""
        if self.app_config:
            return self.save_config(self.app_config, "app")
        return False
    
    def create_default_config(self) -> AppConfig:
        """创建默认应用程序配置"""
        config = AppConfig(
            title="PySide6 Application",
            version="1.0.0",
            # 菜单配置
            menus=[
                MenuConfig(
                    title="项目",
                    toolbars=[
                        ToolbarConfig(
                            barname="文件",
                            items=[
                                {"text": "新建", "callback_name": "new_file", "shortcut": "Ctrl+N"},
                                {"text": "打开", "callback_name": "open_file", "shortcut": "Ctrl+O"},
                                {"text": "保存", "callback_name": "save_file", "shortcut": "Ctrl+S"},
                                {"text": "退出", "callback_name": "exit", "shortcut": "Ctrl+Q", "separator_before": True}
                            ]
                        ),
                        ToolbarConfig(
                            barname="数据库",
                            items=[
                                {"text": "连接", "callback_name": "connect_db"},
                                {"text": "断开", "callback_name": "disconnect_db"}
                            ]
                        )
                    ]
                ),
                MenuConfig(
                    title="编辑",
                    toolbars=[
                        ToolbarConfig(
                            barname="剪贴板",
                            items=[
                                {"text": "复制", "callback_name": "copy", "shortcut": "Ctrl+C"},
                                {"text": "粘贴", "callback_name": "paste", "shortcut": "Ctrl+V"}
                            ]
                        )
                    ]
                ),
                MenuConfig(
                    title="视图",
                    toolbars=[
                        ToolbarConfig(
                            barname="显示选项",
                            items=[
                                {"text": "工具栏", "callback_name": "toggle_toolbar"},
                                {"text": "状态栏", "callback_name": "toggle_statusbar"},
                                {"text": "切换样式", "callback_name": "toggle_style"}
                            ]
                        )
                    ]
                ),
                MenuConfig(
                    title="帮助",
                    toolbars=[
                        ToolbarConfig(
                            barname="关于",
                            items=[
                                {"text": "关于", "callback_name": "show_about"}
                            ]
                        )
                    ]
                )
            ],
            # 停靠窗口配置
            dock_widgets=[
                DockWidgetConfig(
                    title="左侧面板",
                    area="left"
                ),
                DockWidgetConfig(
                    title="右侧面板",
                    area="right"
                ),
                DockWidgetConfig(
                    title="底部面板",
                    area="bottom"
                )
            ]
        )
        
        # 保存默认配置
        self.app_config = config
        self.save_app_config()
        
        return config 